<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Http\Controllers\Controller;
use DB;
use App\Models\Admin;
use App\Models\Role;
use App\Models\Permission;
use Illuminate\Support\Facades\Auth;

class UserController extends Controller {

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request) {
        if ($request->has('search')) {
            $users = Admin::where('user_name', 'like', $request->input('search') . '%')->paginate(10);
            $data = ['users' => $users, 'search' => $request->input('search')];
        } else {
            $users = Admin::paginate(10);
            $data = ['users' => $users];
        }
        $data['roles'] = Role::all();
        return view('admin.user.index', $data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create() {
        $roles = Role::all();
        $permissions = Permission::all();
        return view('admin.user.create', ['roles' => $roles, 'permissions' => $permissions]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request) {
        $rule = [
            'user_name' => 'required',
            'name' => 'required',
            'password' => 'required'
        ];
        $input = $request->all();
        Validator::make($input, $rule)->validate();
        if (Admin::where('user_name', $input['user_name'])->exists()) {
            return ['status' => 0, 'msg' => '用户名已存在'];
        }
        try {
            $admin = Admin::create([
                        'user_name' => $input['user_name'],
                        'name' => $input['name'],
                        'password' => bcrypt($input['password'])
            ]);
            if (isset($input['roles']) && is_array($input['permissions'])) {
                foreach ($input['roles'] as $role) {
                    DB::table('admin_role_users')->insert([
                        'role_id' => $role,
                        'user_id' => $admin->id
                    ]);
                }
            }
            if (isset($input['permissions']) && is_array($input['permissions'])) {
                foreach ($input['permissions'] as $permission) {
                    DB::table('admin_user_permissions')->insert([
                        'permission_id' => $permission,
                        'user_id' => $admin->id
                    ]);
                }
            }
        } catch (\Exception $e) {
            return ['status' => 0, 'msg' => $e->getMessage()];
        }
        return ['status' => 1, 'msg' => '添加成功!'];
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id) {
        if ($id == 1 && Auth::guard('admin')->user()->id != 1) {
            return jump('无权访问');
        }
        $user = Admin::find($id);
        $roles = Role::all();
        $permissions = Permission::all();
        return view('admin.user.edit', ['user' => $user, 'roles' => $roles, 'permissions' => $permissions]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id) {
        $rule = [
            'user_name' => 'required',
            'name' => 'required',
            'password' => 'required'
        ];
        $input = $request->all();
        Validator::make($input, $rule)->validate();
        $user = Admin::find($id);
        $user->user_name = $input['user_name'];
        $user->name = $input['name'];
        if ($request->input('password') != $user->password) {
            $user->password = bcrypt($input['password']);
        }
        try {
            $user->save();
            DB::table('admin_role_users')->where('user_id', $id)->delete();
            if (isset($input['roles']) && is_array($input['roles'])) {
                foreach ($input['roles'] as $role) {
                    DB::table('admin_role_users')->insert([
                        'user_id' => $id,
                        'role_id' => $role
                    ]);
                }
            }
            DB::table('admin_user_permissions')->where('user_id', $id)->delete();
            if (isset($input['permissions']) && is_array($input['permissions'])) {
                foreach ($input['permissions'] as $permission) {
                    DB::table('admin_user_permissions')->insert([
                        'permission_id' => $permission,
                        'user_id' => $id
                    ]);
                }
            }
        } catch (\Exception $e) {
            return ['status' => 0, 'msg' => $e->getMessage()];
        }
        return ['status' => 1, 'msg' => '修改成功!'];
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id) {
        if ($id == 1) {
            return ['status' => 0, 'msg' => '无法删除顶级管理员!'];
        }
        if ($id == Auth::guard('admin')->user()->id) {
            return ['status' => 0, 'msg' => '无法删除自己!'];
        }
        Admin::destroy($id);
        return ['status' => 1, 'msg' => '删除成功!'];
    }

    /**
     * 批量删除
     * @param Request $request
     */
    public function batchDestroy(Request $request) {
        $rule = [
            'ids' => 'required|array',
        ];
        $input = $request->all();
        Validator::make($input, $rule)->validate();
        $userModel = config('admin.database.users_model');
        $userModel::destroy($input['ids']);
        return ['status' => 1, 'msg' => '删除成功!'];
    }

}
